import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import NProgress from 'nprogress'

// 路由组件懒加载
const Layout = () => import('@/layout/index.vue')
const Login = () => import('@/views/Login.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const UserManagement = () => import('@/views/UserManagement.vue')
const NewsManagement = () => import('@/views/NewsManagement.vue')
const CourseManagement = () => import('@/views/CourseManagement.vue')
const MeetingManagement = () => import('@/views/MeetingManagement.vue')
const Profile = () => import('@/views/Profile.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '首页',
          icon: 'House',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/user',
    component: Layout,
    redirect: '/user/management',
    meta: {
      title: '用户管理',
      icon: 'User',
      requiresAuth: true,
      requiresAdmin: true
    },
    children: [
      {
        path: '/user/management',
        name: 'UserManagement',
        component: UserManagement,
        meta: {
          title: '用户管理',
          requiresAuth: true,
          requiresAdmin: true
        }
      }
    ]
  },
  {
    path: '/news',
    component: Layout,
    redirect: '/news/management',
    meta: {
      title: '行业动态',
      icon: 'Document',
      requiresAuth: true
    },
    children: [
      {
        path: '/news/management',
        name: 'NewsManagement',
        component: NewsManagement,
        meta: {
          title: '动态管理',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/course',
    component: Layout,
    redirect: '/course/management',
    meta: {
      title: '课程管理',
      icon: 'Reading',
      requiresAuth: true
    },
    children: [
      {
        path: '/course/management',
        name: 'CourseManagement',
        component: CourseManagement,
        meta: {
          title: '课程管理',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/meeting',
    component: Layout,
    redirect: '/meeting/management',
    meta: {
      title: '会议管理',
      icon: 'Calendar',
      requiresAuth: true
    },
    children: [
      {
        path: '/meeting/management',
        name: 'MeetingManagement',
        component: MeetingManagement,
        meta: {
          title: '会议管理',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    redirect: '/profile/info',
    meta: {
      title: '个人中心',
      icon: 'UserFilled',
      requiresAuth: true
    },
    children: [
      {
        path: '/profile/info',
        name: 'Profile',
        component: Profile,
        meta: {
          title: '个人信息',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue'),
    meta: {
      title: '页面不存在'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 测盟汇管理平台` : '测盟汇管理平台'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isAuthenticated) {
      // 尝试从本地存储恢复登录状态
      const token = localStorage.getItem('token')
      if (token) {
        try {
          await userStore.validateToken()
          if (userStore.isAuthenticated) {
            // 检查管理员权限
            if (to.meta.requiresAdmin && !userStore.isAdmin) {
              ElMessage.error('权限不足')
              next('/dashboard')
              return
            }
            next()
            return
          }
        } catch (error) {
          console.error('Token validation failed:', error)
        }
      }
      
      ElMessage.warning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 检查管理员权限
    if (to.meta.requiresAdmin && !userStore.isAdmin) {
      ElMessage.error('权限不足')
      next('/dashboard')
      return
    }
  }
  
  // 已登录用户访问登录页时重定向到首页
  if (to.path === '/login' && userStore.isAuthenticated) {
    next('/dashboard')
    return
  }
  
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router